// src/main/java/org/example/backend/controller/AdminController.java
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.*;
import org.example.backend.entity.Company;
import org.example.backend.entity.Student;
import org.example.backend.entity.Teacher;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.CompanyRepository;
import org.example.backend.service.CompanyService;
import org.example.backend.service.StudentService;
import org.example.backend.service.TeacherService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    private final UserService userService;
    private final CompanyService companyService;
    private final CompanyRepository companyRepository;
    private final TeacherService teacherService;
    private final StudentService studentService;

    public AdminController(UserService userService, CompanyService companyService, CompanyRepository companyRepository, TeacherService teacherService, StudentService studentService) {
        this.userService = userService;
        this.companyService = companyService;
        this.companyRepository = companyRepository;
        this.teacherService = teacherService;
        this.studentService = studentService;
    }

    /**
     * 创建用户
     */
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@Valid @RequestBody UserManagementDto userDto) {
        try {
            User user = userService.createUser(userDto);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "用户创建成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/users/{userId}")
    public ResponseEntity<?> updateUser(@PathVariable Long userId,
                                      @Valid @RequestBody UserManagementDto userDto) {
        try {
            User user = userService.updateUser(userId, userDto);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "用户更新成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 删除用户（软删除）
     */
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            return ResponseEntity.ok("用户删除成功");
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/users/{userId}")
    public ResponseEntity<?> getUser(@PathVariable Long userId) {
        try {
            User user = userService.getUserById(userId);
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/users")
    public ResponseEntity<PageResponseDto<UserManagementDto>> getUsers(UserQueryDto queryDto,
                                                                       @RequestParam(defaultValue = "0") int page,
                                                                       @RequestParam(defaultValue = "10") int size) {

        // 创建带默认排序的Pageable对象，按id升序排序
        Pageable pageable = PageRequest.of(page, size, Sort.by("id").ascending());

        // 如果queryDto为空，创建一个新的实例
        if (queryDto == null) {
            queryDto = new UserQueryDto();
        }

        // 设置分页参数
        queryDto.setPage(page);
        queryDto.setSize(size);
//        queryDto.setPageable(pageable);

        PageResponseDto<UserManagementDto> users = userService.getUsers(queryDto,pageable);
        return ResponseEntity.ok(users);
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/users/{userId}/reset-password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> resetPassword(@PathVariable Long userId) {
        try {
            userService.resetPassword(userId);
            return ResponseEntity.ok("密码重置成功，默认密码为123456");
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("密码重置失败", e);
            return ResponseEntity.badRequest().body("密码重置失败：" + e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/users/{userId}/toggle-status")
    public ResponseEntity<?> toggleUserStatus(@PathVariable Long userId) {
        try {
            userService.toggleUserStatus(userId);
            return ResponseEntity.ok("用户状态更新成功");
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 审核企业入驻申请
     */
    @PutMapping("/companies/{companyId}/review")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> reviewCompanyApplication(@PathVariable Long companyId,
                                                      @RequestBody CompanyReviewDto reviewDto) {
        try {
            Company company = companyService.reviewCompany(companyId, reviewDto);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业审核完成");
            response.put("company", company);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("企业审核失败", e);
            return ResponseEntity.badRequest().body("审核失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询企业列表
     */
    @GetMapping("/companies")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<Company>> getCompanies(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<Company> companyPage = companyRepository.findAll(pageable);

            PageResponseDto<Company> response = new PageResponseDto<>(
                    companyPage.getContent(),
                    companyPage.getTotalElements(),
                    companyPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取企业列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 根据状态查询企业列表
     */
    @GetMapping("/companies/status/{status}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<Company>> getCompaniesByStatus(
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<Company> companyPage = companyRepository.findByStatus(status, pageable);

            PageResponseDto<Company> response = new PageResponseDto<>(
                    companyPage.getContent(),
                    companyPage.getTotalElements(),
                    companyPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("根据状态获取企业列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取用户详情 (统一接口，根据用户角色返回不同信息)
     */
    @GetMapping("/users/{userId}/detail")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getUserDetail(@PathVariable Long userId) {
        try {
            User user = userService.getUserById(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("user", user);

            // 根据用户角色获取详细信息
            switch (user.getRole()) {
                case STUDENT:
                    Student student = studentService.getStudentByUserId(userId);
                    response.put("detail", student);
                    break;
                case TEACHER:
                    Teacher teacher = teacherService.getTeacherByUserId(userId);
                    response.put("detail", teacher);
                    break;
                case COMPANY:
                    Company company = companyService.getCompanyByUserId(userId);
                    response.put("detail", company);
                    break;
                case ADMIN:
                    response.put("detail", "管理员账户");
                    break;
            }

            return ResponseEntity.ok(response);
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("获取用户详情失败", e);
            return ResponseEntity.badRequest().body("获取用户详情失败：" + e.getMessage());
        }
    }




    /**
     * 管理员更新学生信息（包括邮箱和手机号）
     */
    @PutMapping("/students/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateStudentByAdmin(@PathVariable Long userId,
                                                  @Valid @RequestBody StudentDto studentDto) {
        try {
            // 先更新学生信息
            Student student = studentService.updateStudentByAdmin(userId, studentDto);

            // 同时更新用户邮箱和手机号
            User user = userService.getUserById(userId);
            user.setEmail(studentDto.getEmail());
            user.setPhone(studentDto.getPhone());
            userService.updateUserDirectly(user); // 直接更新用户信息，绕过角色检查

            Map<String, Object> response = new HashMap<>();
            response.put("message", "学生信息更新成功");
            response.put("student", student);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新学生信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 管理员更新教师信息（包括邮箱和手机号）
     */
    @PutMapping("/teachers/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateTeacherByAdmin(@PathVariable Long userId,
                                                  @Valid @RequestBody TeacherDto teacherDto) {
        try {
            // 先更新教师信息
            Teacher teacher = teacherService.updateTeacherByAdmin(userId, teacherDto);

            // 同时更新用户邮箱和手机号
            User user = userService.getUserById(userId);
            user.setEmail(teacherDto.getEmail());
            user.setPhone(teacherDto.getPhone());
            userService.updateUserDirectly(user); // 直接更新用户信息，绕过角色检查

            Map<String, Object> response = new HashMap<>();
            response.put("message", "教师信息更新成功");
            response.put("teacher", teacher);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新教师信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 管理员更新企业信息（包括邮箱和手机号）
     */
    @PutMapping("/companies/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateCompanyByAdmin(@PathVariable Long userId,
                                                  @Valid @RequestBody CompanyDto companyDto) {
        try {
            // 先更新企业信息
            Company company = companyService.updateCompanyByAdmin(userId, companyDto);

            // 同时更新用户邮箱和手机号
            User user = userService.getUserById(userId);
            user.setEmail(companyDto.getContactEmail());
            user.setPhone(companyDto.getContactPhone());
            userService.updateUserDirectly(user); // 直接更新用户信息，绕过角色检查

            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业信息更新成功");
            response.put("company", company);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新企业信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 管理员获取教师列表
     */
    @GetMapping("/teachers")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<TeacherDto>> getTeachers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String teacherNumber,
            @RequestParam(required = false) String department,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<TeacherDto> teacherPage = teacherService.getTeachers(name, teacherNumber, department, page, size);

            PageResponseDto<TeacherDto> response = new PageResponseDto<>(
                    teacherPage.getContent(),
                    teacherPage.getTotalElements(),
                    teacherPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取教师列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

}
